<?php
class ModelCatalogManufacturer extends Model {
	public function addManufacturer($data) {
		$this->db->query("INSERT INTO " . DB_PREFIX . "manufacturer SET name = '" . $this->db->escape((string)$data['name']) . "', sort_order = '" . (int)$data['sort_order'] . "'");

		$manufacturer_id = $this->db->getLastId();

		if (isset($data['image'])) {
			$this->db->query("UPDATE " . DB_PREFIX . "manufacturer SET image = '" . $this->db->escape((string)$data['image']) . "' WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");
		}

		if (isset($data['manufacturer_store'])) {
			foreach ($data['manufacturer_store'] as $store_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "manufacturer_to_store SET manufacturer_id = '" . (int)$manufacturer_id . "', store_id = '" . (int)$store_id . "'");
			}
		}
				
		// SEO URL
		if (isset($data['manufacturer_seo_url'])) {
			foreach ($data['manufacturer_seo_url'] as $store_id => $language) {
				foreach ($language as $language_id => $keyword) {
					if (!empty($keyword)) {
						$this->db->query("INSERT INTO " . DB_PREFIX . "seo_url SET store_id = '" . (int)$store_id . "', language_id = '" . (int)$language_id . "', query = 'manufacturer_id=" . (int)$manufacturer_id . "', keyword = '" . $this->db->escape($keyword) . "'");
					}
				}
			}
		}
		
		$this->cache->delete('manufacturer');

		return $manufacturer_id;
	}

	public function editManufacturer($manufacturer_id, $data) {
		$this->db->query("UPDATE " . DB_PREFIX . "manufacturer SET name = '" . $this->db->escape((string)$data['name']) . "', sort_order = '" . (int)$data['sort_order'] . "' WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");

		if (isset($data['image'])) {
			$this->db->query("UPDATE " . DB_PREFIX . "manufacturer SET image = '" . $this->db->escape((string)$data['image']) . "' WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");
		}

		$this->db->query("DELETE FROM " . DB_PREFIX . "manufacturer_to_store WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");

		if (isset($data['manufacturer_store'])) {
			foreach ($data['manufacturer_store'] as $store_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "manufacturer_to_store SET manufacturer_id = '" . (int)$manufacturer_id . "', store_id = '" . (int)$store_id . "'");
			}
		}

		$this->db->query("DELETE FROM `" . DB_PREFIX . "seo_url` WHERE query = 'manufacturer_id=" . (int)$manufacturer_id . "'");

		if (isset($data['manufacturer_seo_url'])) {
			foreach ($data['manufacturer_seo_url'] as $store_id => $language) {
				foreach ($language as $language_id => $keyword) {
					if (!empty($keyword)) {
						$this->db->query("INSERT INTO `" . DB_PREFIX . "seo_url` SET store_id = '" . (int)$store_id . "', language_id = '" . (int)$language_id . "', query = 'manufacturer_id=" . (int)$manufacturer_id . "', keyword = '" . $this->db->escape($keyword) . "'");
					}
				}
			}
		}

		$this->cache->delete('manufacturer');
	}

	public function deleteManufacturer($manufacturer_id) {
		$this->db->query("DELETE FROM `" . DB_PREFIX . "manufacturer` WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");
		$this->db->query("DELETE FROM `" . DB_PREFIX . "manufacturer_to_store` WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");
		$this->db->query("DELETE FROM `" . DB_PREFIX . "seo_url` WHERE query = 'manufacturer_id=" . (int)$manufacturer_id . "'");

		$this->cache->delete('manufacturer');
	}

	public function getManufacturer($manufacturer_id) {
		$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "manufacturer WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");

		return $query->row;
	}

	public function getManufacturers($data = array()) {
		$sql = "SELECT * FROM " . DB_PREFIX . "manufacturer";

		if (!empty($data['filter_name'])) {
			$sql .= " WHERE name LIKE '" . $this->db->escape((string)$data['filter_name']) . "%'";
		}

		$sort_data = array(
			'name',
			'sort_order'
		);

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY name";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}

		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getManufacturerStores($manufacturer_id) {
		$manufacturer_store_data = array();

		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "manufacturer_to_store WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");

		foreach ($query->rows as $result) {
			$manufacturer_store_data[] = $result['store_id'];
		}

		return $manufacturer_store_data;
	}
	
	public function getManufacturerSeoUrls($manufacturer_id) {
		$manufacturer_seo_url_data = array();
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE query = 'manufacturer_id=" . (int)$manufacturer_id . "'");

		foreach ($query->rows as $result) {
			$manufacturer_seo_url_data[$result['store_id']][$result['language_id']] = $result['keyword'];
		}

		return $manufacturer_seo_url_data;
	}
	
	public function getTotalManufacturers() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "manufacturer");

		return $query->row['total'];
	}


	// 对manufacturer_description表的处理
    // 获取品牌的总数量，根据language_id获取
	public function getTotalManufacturersByLanguage()
    {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "manufacturer_description WHERE language_id = '". $this->config->get('config_language_id') ."'");

        return $query->row['total'];
    }

    // 获取品牌的数组，根据language_id获取
    public function getManufacturerDescriptions($data = array()) {
        $sql = "SELECT * FROM " . DB_PREFIX . "manufacturer_description WHERE language_id = '". $this->config->get('config_language_id') ."'";

        if (!empty($data['filter_name'])) {
            $sql .= " AND name LIKE '" . $this->db->escape((string)$data['filter_name']) . "%'";
        }

        $sort_data = array(
            'name',
            'sort_order'
        );

        if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
            $sql .= " ORDER BY " . $data['sort'];
        } else {
            $sql .= " ORDER BY name";
        }

        if (isset($data['order']) && ($data['order'] == 'DESC')) {
            $sql .= " DESC";
        } else {
            $sql .= " ASC";
        }

        if (isset($data['start']) || isset($data['limit'])) {
            if ($data['start'] < 0) {
                $data['start'] = 0;
            }

            if ($data['limit'] < 1) {
                $data['limit'] = 20;
            }

            $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
        }

        $query = $this->db->query($sql);

        return $query->rows;
    }

    // 获取品牌的数组，根据language_id 和 manufacturer_id 获取
    public function getManufacturerDescription($manufacturer_id) {
        $query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "manufacturer_description WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");

        $query_data = $query->rows;

        if (! count($query_data)) return null;

        $this->load->model('tool/image');

        $data = [];
        foreach($query_data as $manufacturer_description)
        {
            if ($manufacturer_description['image']) {
                $manufacturer_description['thumb'] = $this->model_tool_image->resize($manufacturer_description['image'], 100, 100);
            } else {
                $manufacturer_description['thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
            }

            // 对应的店铺
            $manufacturer_description['manufacturer_store'] = $this->getManufacturerDescriptionStores($manufacturer_description['manufacturer_description_id']);

            $data[$manufacturer_description['language_id']] = $manufacturer_description;
        }

        return $data;
    }

    // 获取品牌对应的店铺，根据language_id 和 manufacturer_id 获取
    public function getManufacturerDescriptionStores($manufacturer_description_id) {
        $manufacturer_store_data = array();

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "manufacturer_description_to_store WHERE manufacturer_description_id = '" . (int)$manufacturer_description_id . "'");

        foreach ($query->rows as $result) {
            $manufacturer_store_data[] = $result['store_id'];
        }

        return $manufacturer_store_data;
    }

    // 保存品牌详情的数据（）
    public function addManufacturerAndManufacturerDescription($data) {

	    // 保存数据到manufacturer表
        $language_id = $this->config->get('config_language_id');
        $manufacturer_data = [
            'name'                 => $data['manufacturer_description'][$language_id]['name'],
            'sort_order'           => $data['manufacturer_description'][$language_id]['sort_order'],
            'image'                => $data['manufacturer_description'][$language_id]['image'],
            'manufacturer_store'   => $data['manufacturer_description'][$language_id]['manufacturer_store'],
            'manufacturer_seo_url' => $data['manufacturer_seo_url'],
        ];
        $manufacturer_id = $this->addManufacturer($manufacturer_data);

        // 保存数据到manufacturer_description表
        foreach($data['manufacturer_description'] as $language_id => $manufacturer_description)
        {
            $this->db->query("INSERT INTO " . DB_PREFIX . "manufacturer_description SET name = '" . $this->db->escape((string)$manufacturer_description['name']) . "', sort_order = '" . (int)$manufacturer_description['sort_order'] . "', language_id = '". $language_id ."', manufacturer_id = '". $manufacturer_id ."'");

            $manufacturer_description_id = $this->db->getLastId();

            if (isset($manufacturer_description['image'])) {
                $this->db->query("UPDATE " . DB_PREFIX . "manufacturer_description SET image = '" . $this->db->escape((string)$manufacturer_description['image']) . "' WHERE manufacturer_description_id = '" . (int)$manufacturer_description_id . "'");
            }

            if (isset($manufacturer_description['manufacturer_store'])) {
                foreach ($manufacturer_description['manufacturer_store'] as $store_id) {
                    $this->db->query("INSERT INTO " . DB_PREFIX . "manufacturer_description_to_store SET manufacturer_description_id = '" . (int)$manufacturer_description_id . "', store_id = '" . (int)$store_id . "'");
                }
            }
        }

        return $manufacturer_id;
    }

    // 更新品牌详情数据
    public function editManufacturerAndManufacturerDescription($manufacturer_id, $data) {

	    // 更新manufacturer表的信息
        $language_id = $this->config->get('config_language_id');
        $manufacturer_data = [
            'name'                 => $data['manufacturer_description'][$language_id]['name'],
            'sort_order'           => $data['manufacturer_description'][$language_id]['sort_order'],
            'image'                => $data['manufacturer_description'][$language_id]['image'],
            'manufacturer_store'   => $data['manufacturer_description'][$language_id]['manufacturer_store'],
            'manufacturer_seo_url' => $data['manufacturer_seo_url'],
        ];

        $this->editManufacturer($manufacturer_id, $manufacturer_data);

        // 更新manufacturer_description表的信息
        foreach($data['manufacturer_description'] as $language_id => $manufacturer_description)
        {
            $this->db->query("UPDATE " . DB_PREFIX . "manufacturer_description SET name = '" . $this->db->escape((string)$manufacturer_description['name']) . "', sort_order = '" . (int)$manufacturer_description['sort_order'] . "' WHERE manufacturer_description_id = '" . (int)$manufacturer_description['manufacturer_description_id'] . "'");

            if (isset($manufacturer_description['image'])) {
                $this->db->query("UPDATE " . DB_PREFIX . "manufacturer_description SET image = '" . $this->db->escape((string)$manufacturer_description['image']) . "' WHERE manufacturer_description_id = '" . (int)$manufacturer_description['manufacturer_description_id'] . "'");
            }

            $this->db->query("DELETE FROM " . DB_PREFIX . "manufacturer_description_to_store WHERE manufacturer_description_id = '" . (int)$manufacturer_description['manufacturer_description_id'] . "'");

            if (isset($manufacturer_description['manufacturer_store'])) {
                foreach ($manufacturer_description['manufacturer_store'] as $store_id) {
                    $this->db->query("INSERT INTO " . DB_PREFIX . "manufacturer_description_to_store SET manufacturer_description_id = '" . (int)$manufacturer_description['manufacturer_description_id'] . "', store_id = '" . (int)$store_id . "'");
                }
            }

        }
    }

    // 删除品牌数据
    public function deleteManufacturerAndManufacturerDescription($manufacturer_id) {

	    // 删除manufacturer表的数据，根据manufacturer_id
	    $this->deleteManufacturer($manufacturer_id);

	    // 删除manufacturer_description
        $query_data = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "manufacturer_description WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");
        $manufacturer_description_ids = array_column($query_data->rows, 'manufacturer_description_id');
        $manufacturer_description_ids = trim(implode(',', $manufacturer_description_ids), ',');

        $this->db->query("DELETE FROM `" . DB_PREFIX . "manufacturer_description` WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");
        $this->db->query("DELETE FROM `" . DB_PREFIX . "manufacturer_description_to_store` WHERE manufacturer_description_id IN (" . $manufacturer_description_ids . ")");
    }
}
